package com.ibangnuo.manage.service.commercial;

import com.ibangnuo.framework.domain.Agent;
import com.ibangnuo.framework.domain.CommercialMigration;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.User;
import com.ibangnuo.framework.domain.request.commercial.CommercialMigrationRequest;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.ObjectResult;
import com.ibangnuo.framework.model.response.QueryResponseResult;
import com.ibangnuo.framework.model.response.QueryResult;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.CommercialMigrationRepository;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: wwy
 * @Date: 2020-03-11 9:36
 */
@Service
public class CommercialMigrationService {
    @Autowired
    private CommercialRepository commercialRepository;

    @Autowired
    private CommercialMigrationRepository commercialMigrationRepository;
    @Autowired
    private AgentRepository agentRepository;
    /**
     * 迁移操作
     * 1.修改商户表中代理商字段
     * 2.保存迁移记录到商户迁移表
     * @param commercialMigration
     * @return
     */
    public ObjectResult migrate(CommercialMigration commercialMigration){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //Agent agent = agentRepository.findByUserId(user.getId());
        if(commercialMigration == null){
            return new ObjectResult(CommonCode.FAIL,null);
        }
        CommercialTenant commercialTenant = this.getCommercialTenantById(commercialMigration.getCommercialTenantId());
        if(commercialTenant == null){
            Map<String,String> map = new HashMap<>();
            map.put("message","迁移商户不存在");
            return new ObjectResult(CommonCode.FAIL,map);
        }
        commercialMigration.setOldAgentId(commercialTenant.getAgentId());
        Agent agent = this.getAgentById(commercialTenant.getAgentId());
        commercialTenant.setAgentId(commercialMigration.getNewAgentId());
        commercialRepository.save(commercialTenant);
        commercialMigration.setCreateTime(new Date());

        commercialMigration.setOldAgentName(agent.getCompanyName());
        Agent newAgent = this.getAgentById(commercialMigration.getNewAgentId());
        commercialMigration.setNewAgentName(newAgent.getCompanyName());
        commercialMigration.setNumber(String.valueOf(PrimaryKeyUtil.nextId()));
        commercialMigration.setCommercialTenantName(commercialTenant.getCompanyName());
        commercialMigrationRepository.save(commercialMigration);
        return new ObjectResult(CommonCode.SUCCESS,null);
    }

    /**
     * 批量迁移
     * @param commercialMigrationList
     * @return
     */
    public ObjectResult migrateList(List<CommercialMigration> commercialMigrationList){
        for (CommercialMigration commercialMigration : commercialMigrationList) {
            if(commercialMigration == null){
                return new ObjectResult(CommonCode.FAIL,null);
            }
            CommercialTenant commercialTenant = this.getCommercialTenantById(commercialMigration.getCommercialTenantId());
            if(commercialTenant == null){
                Map<String,String> map = new HashMap<>();
                map.put("message","迁移商户不存在");
                return new ObjectResult(CommonCode.FAIL,map);
            }
            commercialMigration.setOldAgentId(commercialTenant.getAgentId());
            Agent agent = this.getAgentById(commercialTenant.getAgentId());
            commercialTenant.setAgentId(commercialMigration.getNewAgentId());
            commercialRepository.save(commercialTenant);
            commercialMigration.setCreateTime(new Date());

            commercialMigration.setOldAgentName(agent.getCompanyName());
            Agent newAgent = this.getAgentById(commercialMigration.getNewAgentId());
            commercialMigration.setNewAgentName(newAgent.getCompanyName());
            commercialMigration.setNumber(String.valueOf(PrimaryKeyUtil.nextId()));
            commercialMigration.setCommercialTenantName(commercialTenant.getCompanyName());
            commercialMigrationRepository.save(commercialMigration);

        }
        return new ObjectResult(CommonCode.SUCCESS,null);

    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @param commercialMigrationRequest
     * @return
     */
    public QueryResponseResult findList(int page, int size, CommercialMigrationRequest commercialMigrationRequest){
        if(commercialMigrationRequest == null){
            commercialMigrationRequest = new CommercialMigrationRequest();
        }
        page = commercialMigrationRequest.getPage();
        size = commercialMigrationRequest.getSize();
        CommercialMigration commercialMigration = new CommercialMigration();
        if(StringUtils.isNotEmpty(commercialMigrationRequest.getCommercialTenantName())){
            commercialMigration.setCommercialTenantName(commercialMigrationRequest.getCommercialTenantName());
        }
        if(StringUtils.isNotEmpty(commercialMigrationRequest.getNumber())){
            commercialMigration.setNumber(commercialMigrationRequest.getNumber());
        }

        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("commercialTenantName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("oldAgentName",ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("number",ExampleMatcher.GenericPropertyMatchers.contains());

        Example<? extends CommercialMigration> example = Example.of(commercialMigration,exampleMatcher);
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        if (page <= 0) {
            page = 1;
        }
        page = page - 1;
        if (size <= 0) {
            size = 10;
        }
        Pageable pageable = PageRequest.of(page, size,sort);
        Page<? extends CommercialMigration> all = commercialMigrationRepository.findAll(example, pageable);
        QueryResult queryResult = new QueryResult();
        queryResult.setTotal(all.getTotalElements());
        queryResult.setList(all.getContent());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);

    }


    /**
     * 根据id查询商户
     * @param id
     * @return
     */
    private CommercialTenant getCommercialTenantById(String id){
        Optional<CommercialTenant> optional = commercialRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 根据id查询代理商
     * @param id
     * @return
     */
    private Agent getAgentById(String id){
        Optional<Agent> optional = agentRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
}
